package com.zmn.brs.admin.controller.event;

import com.alibaba.fastjson.JSONObject;
import com.zmn.brs.business.interfaces.rule.AlarmRuleBService;
import com.zmn.brs.model.entity.event.Event;
import com.zmn.brs.model.entity.event.EventQuery;
import com.zmn.brs.model.entity.objective.event.ObjectiveEvent;
import com.zmn.brs.model.entity.scene.Scene;
import com.zmn.brs.model.entity.threshold.Threshold;
import com.zmn.brs.services.interfaces.event.EventService;
import com.zmn.brs.services.interfaces.objective.event.ObjectiveEventService;
import com.zmn.brs.services.interfaces.scene.SceneService;
import com.zmn.brs.services.interfaces.threshold.ThresholdService;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.mcc.dubbo.dto.DubboConsts;
import com.zmn.okr.common.constant.ObjectiveMasterTypeConst;
import com.zmn.okr.common.model.base.PageDRO;
import com.zmn.okr.common.model.dio.objective.ObjectiveDIO;
import com.zmn.okr.common.model.dio.objective.ObjectiveQueryDIO;
import com.zmn.okr.dubbo.interfaces.objective.ObjectiveRemoteService;
import com.zmn.plat.common.dictionary.StatusEnum;
import org.apache.dubbo.config.annotation.Reference;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 描述: 业务场景事件配置
 *
 * @author chongw
 * @since 2021-05-27
 **/
@Controller
@RequestMapping(value = "/brs/event/")
public class EventListController extends EventBaseController {

    @Resource
    private EventService eventService;

    @Resource
    private SceneService sceneService;

    @Resource
    private ObjectiveEventService objectiveEventService;

    @Resource
    private AlarmRuleBService alarmRuleBService;

    @Resource
    private ThresholdService thresholdService;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    ObjectiveRemoteService objectiveRemoteService;

    /**
     * 描述: 业务场景事件列表
     * @param query 查询条件
     * @return org.springframework.web.servlet.ModelAndView
     **/
    @RequestMapping(value = "list")
    public ModelAndView list(@ModelAttribute EventQuery query) {
        if (StringUtil.isNotBlank(query.getTimeSearch())) {
            String[] timeRangeArray = query.getTimeSearch().split("-");
            query.setStartUpdateTime(timeRangeArray[0].trim() + " 00:00:00");
            query.setEndUpdateTime(timeRangeArray[1].trim() + " 23:59:59");
        }
        List<Event> list = eventService.listPageByQuery(query);
        ModelAndView mv = new ModelAndView("event/list");
        mv.addObject("items",list);
        mv.addObject("vo", query);
        mv.addObject("flag",2);
        return mv;
    }

    /**
     * 描述: 查询业务场景事件信息
     * @param query 查询条件
     * @return org.springframework.web.servlet.ModelAndView
     **/
    @RequestMapping(value = "info")
    public ModelAndView info(@ModelAttribute EventQuery query) {
        Event data = Optional.ofNullable(eventService.findById(query.getEventId())).orElse(Event.builder().build());
        //查询规则ID
        Integer ruleId = alarmRuleBService.findRuleIdByEventId(data.getEventId());
        if(ruleId != null){
           Threshold threshold = Optional.ofNullable(thresholdService.findCommonThresholdByRuleId(ruleId)).orElse(Threshold.builder().build());
           data.setCommon(JSONObject.parseObject(threshold.getThresholdValue()));
        }
        Scene scene = Optional.ofNullable(sceneService.findById(data.getSceneId())).orElse(Scene.builder().build());
        //查询目标事件
        ObjectiveEvent objectiveEvent = Optional.ofNullable(objectiveEventService.findByEventId(query.getEventId())).orElse(ObjectiveEvent.builder().build());
        ModelAndView mv = new ModelAndView("event/info");
        mv.addObject("data",data);
        mv.addObject("objectiveEvent",objectiveEvent);
        mv.addObject("flag",1);
        mv.addObject("eventId",data.getEventId());
        mv.addObject("sceneId", data.getSceneId());
        mv.addObject("scene", scene);
        return mv;
    }

    /**
     * 描述: okr配置目标信息
     * @return org.springframework.web.servlet.ModelAndView
     **/
    @RequestMapping(value = "getObjectiveList")
    public ModelAndView getObjectiveList(@ModelAttribute ObjectiveQueryDIO query,Integer plat,Integer orgTwoId,Integer orgOneId) {
        Optional<ObjectiveQueryDIO> optional = Optional.ofNullable(query).map(o -> {
            o.setPageSize(Optional.ofNullable(o.getPageSize()).orElse(20));
            o.setPagesNumber(Optional.ofNullable(o.getPagesNumber()).orElse(1));
            o.setObjMasterType(ObjectiveMasterTypeConst.MASTERTYPE_ALL_DEPT);
            return o;
        });
        Date now = DateUtil.getNow();
        //获取当年1月1日
        Date startDate = DateUtil.getYearStart(new DateTime(now).getYear());
        query.setStartDate(startDate);
        query.setEndDate(now);
        query.setStatus(StatusEnum.ENABLE.getCode());
        query.setOrgId(plat);
        ModelAndView mv = new ModelAndView("event/objective/list");
        mv.addObject("vo", optional.get());
        mv.addObject("plat", plat);
        mv.addObject("orgTwoId", orgTwoId);
        mv.addObject("orgOneId", orgOneId);
        try {
            ResponseDTO<PageDRO<ObjectiveDIO>> responseDTO = objectiveRemoteService.listPageObjectiveByDIO(optional.get());
            if (responseDTO.isSuccess()) {
                List<ObjectiveDIO> items = responseDTO.getData().getItemList();
                mv.addObject("items", items);
            }
            mv.addObject("totalCount", responseDTO.getData().getTotalCount());
        }catch (Exception e){
            logger.error("OKR目标管理列表调用异常，异常信息：" + e);
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 描述: 事件规则管理
     * @param query 查询条件
     * @return org.springframework.web.servlet.ModelAndView
     **/
    @RequestMapping(value = "ruleManager")
    public ModelAndView ruleManager(@ModelAttribute EventQuery query) {
        Event data = eventService.findById(query.getEventId());
        ModelAndView mv = new ModelAndView("event/info");
        mv.addObject("data",data);
        mv.addObject("flag",2);
        mv.addObject("eventId",query.getEventId());
        return mv;
    }



}